<?
App::uses('HttpSocket', 'Network/Http');
App::uses('CakeTime', 'Utility');

define('API_SUCCESS', 1);
define('API_NOT_MODIFIED', 2);
define('API_ERROR', 3);

/**
 * @property Gevent $Gevent Event model
 * @property Sync $Sync Sync model
 */
class SyncShell extends AppShell {
    
    public $uses = array('Sync','Gevent');
    
    public function main() {
        $this->out('Use: Console/cake sync sync to perform G+ synch');
    }
    
    public function sync() {
        $this->out('Ready to go!');
        $syncObj = $this->Sync->find('all');
        foreach($syncObj as $sync){
            $this->syncEvents($sync);
            //sleep(3);
        }
        $this->out("Synchronization completed");
    }
    
    
    private function syncEvents($sync){
        
        $pageId = $sync['Sync']['pageid'];
        if(!$pageId){
            $pageId = $sync['Chapter']['gp_page'];
        }
        if(!$pageId){
            return API_ERROR;
        }
        $etag = $sync['Sync']['etag'];
        $this->out("Performing synch for page: " + $pageId);
        
        
        $request = array(
            'method' => 'GET',
            'uri' => 'https://www.googleapis.com/plus/v1/people/'.$pageId.'/activities/public?key=AIzaSyAUBeODPoy95_dpzs-D9Nn6xleuQNIwxwo&fields=items(id%2Cobject(attachments(displayName%2Cid%2CobjectType%2Curl)%2Ccontent)%2Cprovider%2Cpublished%2Cupdated)'
        );
        if($etag != null && !empty($etag)){
            $request['header'] = array(
                'If-None-Match' => $etag
            );
        }
        
        $http = new HttpSocket();
        $response = $http->request($request);
        
        if($response->code == 200){
            //got new events
            try {
                $this->parsePageResult($sync, $response);
            } catch (Exception $exc) {
                $this->out($exc->getTraceAsString());
            }

            
            
            return API_SUCCESS;
        } elseif($response->code == 304) {
            //all synced
            return API_NOT_MODIFIED;
        }
        return API_ERROR;
    }
    
    
    private function parsePageResult($sync, $response){
        if($response == null){
            LogError('Sync error: either response or pageid are null');
            throw new Exception("Sync error: either response or pageid are null");
        }
        $pageId = $sync['Sync']['pageid'];
        if(!$pageId){
            $pageId = $sync['Chapter']['gp_page'];
        }
        
        $etag = null;
        if(!empty($response->headers['ETag'])){
            $etag = $response->headers['ETag'];
        }
        $sync['Sync']['etag'] = $etag;
        $body = json_decode($response->body, false);
        
        foreach($body->items as $item){
            
            if(empty($item->object) || !isset($item->object->attachments) || $item->object->attachments[0]->objectType != 'event' || $item->provider->title != 'Events'){
                continue;
            }
            
            $data = $this->Gevent->create();
            $data['Gevent']['name'] = $item->object->attachments[0]->displayName;
            $data['Gevent']['desc'] = $item->object->content;
            $data['Gevent']['chapter_id'] = (empty($sync['Sync']['chapter_id']) ? 0 : $sync['Sync']['chapter_id'] );
            $data['Gevent']['eventid'] = $item->id;
            $data['Gevent']['created'] = CakeTime::format('Y-m-d H:i:s',$item->published);
            $data['Gevent']['eventurl'] = $item->object->attachments[0]->url;
            $this->Gevent->save($data);
        }
        $this->Sync->save($sync);
    }
    
}
?>